<template>
  <div class="rule-box">
    <div class="rule-title">
      <div class="word">
        规章制度及流程公示
      </div>
      <div class="add-btn">
        <el-button
          @click="uploadRules"
          v-if="root === 0"
        >
          上传公示文件
        </el-button>
      </div>
    </div>
    <div class="table-box">
      <el-table :data="fileData" border style="width: 100%" stripe>
        <el-table-column type="index" align="center"/>
        <el-table-column prop="file_name" label="名称" align="center"/>
        <el-table-column label="上传时间" align="center">
          <template #default="{row}">
            {{computeDate(row.created_at)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button
              type="primary"
              @click="previewRules(row)"
            >
              预览
            </el-button>
            <el-button
              type="warning"
              @click="downloadRules(row)"
            >
              下载
            </el-button>
            <el-button
              type="danger"
              v-if="root === 0"
              @click="delRules(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <div class="upload-box">
    <el-dialog
        v-model="dialogVisible"
        width="500"
        :before-close="cancelUpload"
    >
      <el-form
          :model="uploadForm"
          :rules="uploadRules"
          ref="uploadFormRef"
      >
        <!--<el-form-item>-->
          <el-upload
              class="upload-demo"
              name="file"
              :action="uploadURL"
              v-model:file-list="uploadForm.file"
              :auto-upload="false"
              :on-change="onchange"
              style="margin-bottom: 2vw"
          >
            <el-button>点击选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                单次只可上传一个文件,仅支持pdf格式
              </div>
            </template>
          </el-upload>
        <!--</el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="submitRule(uploadFormRef)">
            上传
          </el-button>
          <el-button @click="cancelUpload">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {ElButton, ElForm, ElMessage, ElUpload, ElFormItem, ElIcon} from "element-plus"
import {ref} from "vue-demi"
import {onMounted, reactive} from "vue"
import {getrules, previewrule, downloadrule, delrule} from "@/api/index.js"
import axios from "axios"
import {computeDate} from "@/lib/utils"
import {useRouter} from "vue-router"
import emitter from "@/lib/eventBus"
import {baseurl, previewYRL} from "@/api/http"


let root
let fileData = ref([])
let dialogVisible = ref(false)
let uploadURL = `${baseurl}/uploadrule`
let fileList = ref([])
const uploadFormRef = ref()
let uploadForm = reactive({
  file:[],
})
let arr = ref([])
const router = useRouter()


onMounted(()=>{
  emitter.emit('home_menu','/rule')
  const info = JSON.parse(localStorage.getItem('syhyDocManSys'))
  root = info.root
  getRuleList()
})


const  handleExceed = () => {
  uploadForm.file = []
  return ElMessage({
    type:'warning',
    message:'单次只能上传一个文件'
  })
}
const uploadRules = () => {
  dialogVisible.value = true
}

const onchange = (file)=>{
  arr.value.push(file.raw)
  console.log(file.raw)
}

const submitRule = async () => {
  try {
    window.source = axios.CancelToken.source(); // 这里初始化source对象
    const name = arr.value[0].type
    // console.log(name,name !== "application/pdf")
    // return
    // if(name !== "application/pdf"){
    //   dialogVisible.value = false
    //   uploadForm.file = []
    //   arr.value = []
    //   await getRuleList()
    //   return ElMessage({
    //     type:'error',
    //     message:'不支持除docx以外格式的文件'
    //   })
    // }
    if(arr.value.length === 0){
      return ElMessage({
        type:'warning',
        message:'请选择文件'
      })
    } else {
      let fd = new FormData();
      fd.append('file', arr.value[0])
      axios({
        url: uploadURL,       //上传服务器接口
        method: 'post',
        data: fd,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      },  {
        cancelToken: window.source.token
      }).then((res) => {
        if(res.data.code === 200){
          ElMessage({
            message: '上传成功!',
            type: 'success',
          })
          getRuleList()
          dialogVisible.value = false
          uploadForm.file = []
          arr.value = []
        } else if (res.data.code === 402) {
          ElMessage({
            message: '不支持除docx以外格式的文件',
            type: 'warning',
          })
          getRuleList()
          dialogVisible.value = false
          uploadForm.file = []
          arr.value = []
        } else {
          ElMessage({
            message: '上传失败!',
            type: 'warning',
          })
          dialogVisible.value = false
          uploadForm.file = []
          arr.value = []
        }
      })
    }
  } catch (e) {
    console.log(e)
  }
}
// 取消上传
const cancelUpload = () => {
  // window.source()
  dialogVisible.value = false
  uploadForm.file = []
}

const previewRules = async (row) => {
  try {
    console.log(row)
    if(row.type !== "pdf") {
      return ElMessage({
        type:'warning',
        message:'仅能预览pdf件'
      })
    } else {
      await window.open(`${previewYRL}/previewR?id=${row.id}`)
      // await router.push({
      //   path: "/previewR",
      //   query: {
      //     id: row.id
      //   }
      // })
      // const resolved = router.resolve({
      //   path: "/previewR",
      //   query: {
      //     id: row.id
      //   }
      // });
      // await window.open(resolved.href, '_blank');
    }
  } catch (e) {
    console.log(e)
  }
}
const downloadRules = async (row) => {
  try {
    const response = await downloadrule({ruleId:row.id})
    const blob = new Blob([response.data],{type:row.mime})
    const filename = row.file_name + '.' + row.type

    //创建a标签下载
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (e) {
    console.log(e)
  }

}
const delRules = async (row) => {
  const {data:res} = await delrule({ruleId:row.id})
  if(res.code === 200){
    getRuleList()
    return ElMessage({
      type:'success',
      message:'删除成功!'
    })
  } else if (res.code === 400) {
    getRuleList()
    return ElMessage({
      type:'error',
      message:'该文件不存在!'
    })
  } else {
    getRuleList()
    return ElMessage({
      type:'error',
      message:'删除失败,请重新尝试'
    })
  }
}
const getRuleList = async () => {
  try {
    const {data:res} = await getrules()
    if(res.code === 200){
      fileData.value = res.data
    } else if (res.code === 201){
      fileData.value = res.data
      return ElMessage({
        type:'info',
        message:'暂无公示信息'
      })
    } else {
      return ElMessage({
        type:'warning',
        message:'请求错误'
      })
    }
  } catch (e) {
    console.log(e)
  }
}


</script>

<style scoped lang="less">
.rule-box{
  height: 100vh;
  width: 98vw;
  margin-left: 4.5vw;
  box-sizing: border-box;
  .rule-title{
    width: 90%;
    margin: 4vh auto;
    display: flex;
    justify-content: space-between;
    .word{
      font-size: 3vh;
      letter-spacing: 3px;
    }
    .add-btn{}
  }
  .table-box{

    width: 85vw;
    margin: 0 auto;
  }
}
.el-table{
  padding: 15px;
  height:85vh;
}
:deep(.el-form-item__content){
  justify-content: center !important;
}
</style>
